﻿module Sustainalytics.Common {

    import Authentication = Sustainalytics.Authentication;


    var mod = angular.module(commonModuleName);

    mod.factory('staticObjects', ['$rootScope', 'notificationFactory', '$location', ($rootScope, notificationFactory, $location) => {
        var getMessageByInternalCode = internalCode => {
            switch (internalCode) {
                case 1000:
                    return "Another report already generating.";
                    
                case 1001:
                    return "Generating the report failed - Please contact your Administrator";
                    
                case 1002:
                    return "Total number of concurrent users per application reached!";
                    
                case 1003:
                    return "Login failed";
                    
                case 'IncorrectUsernamePasswordCombination':
                case 1004:
                    return "The combination of username and password is incorrect. Please check and try again.";
                    
                case 'InvalidEmailAddres':
                case 1005:
                    return "The e-mail address was not found or it is not currently associated with any account. Please contact us for further information.";
                    
                case 'InactiveAccount':
                case 1006:
                    return 'Your account is currently inactive, please <a href="mailto:client@sustainalytics.com">contact us</a> if you would like to regain access.';

                case 'NoApiAccess':
                    return 'The account does not have api access. Please contact your client advisor.';

                case 'ExpiredPassword':
                case 1007:
                    return "To (re)activate your password please click Reset Password above. An email will be sent to you with instructions. If you don't receive this email in the next 15 minutes please contact your client advisor.";
                    
                case 1008:
                    return "The temporary key has expired. Please use the forgot password link to create a new one.";
                    
                case 1009:
                    return "The temporary key is no longer valid.";
                    
                case 1010:
                    return "There was a critical error processing your request. The platform administrators have been notified.";
                    
                case 1011:
                    return "There was a critical error processing your request. The platform administrators have been notified.";
                    
                case 1012:
                    return "There was an error changing your password. Please try again later.";
                    
                case 1019:
                    return "There was a critical error processing your request. The platform administrators have been notified.";
                    
                case 5105:
                    return "The item(s) could not be added to your portfolio.Please contact your client advisor for details.";
                    
                case 9999:
                    return "You are not authorized to use that resource.";

                case 5107:
                    return "Company security already present in matched grid!";
                    
                default:
                    return "An error has occurred. Please contact your administrator!";
            }
        };

        var staticObjects: IStaticObjects = {
            getMessageByInternalCode: getMessageByInternalCode,
            reportTypes: [{ id: 1, name: "Company Report" }, { id: 2, name: "Relative Analysis Report" }],
            companies: [{ id: "7bafdbd0-2e9c-4048-8a85-000bbf41af01", name: "Default" }],
            comparativeGroups: [{ id: 1, name: "Peer Group" }, { id: 2, name: "Industry Group" }],
            matrixes: [{ id: "9c19a43d-a9f6-49f1-8452-061f32d0f6fc", name: "Default Matrix" }],
            referenceUniverses:
            [
                { id: "9c19a43d-a9f6-49f1-8452-061f32d0f6fc", name: "Reference Universe 1" },
                { id: "b8cc3ca4-045b-4987-b1ee-402f7a058c14", name: "Reference Universe 2" },
                { id: "0bcc0578-520b-4a72-93c6-a863c2d2321f", name: "Reference Universe 3" }
            ],
            apiBaseUrl: "/reports/api/",
            authBaseUrl: "/auth",
            baseUrl: "/accountsserv",
            screeningToolBaseUrl: "/screening",
            screeningToolServBaseUrl: "/screeningtoolserv/api/v1",
            resourcePermissions: "",
            portfolioBaseUrl: "/portfolioserv",
            reportResponse: { Status: "", Finished: "", FilePath: "", Created: "", Error: "", ReportType: "" },
            reportResponseBroadcast: reportNotification => {
                staticObjects.reportResponse = reportNotification;
                $rootScope.$broadcast('handleBroadcast');
            },
            getGCCSAssesmentByValue: (value: number) => {
                switch (value) {
                    case 0:
                        return "Compliant";
                    case 1:
                        return "Watchlist";
                    case 2:
                        return "Non-Compliant";
                    default:
                        return "";
                }
            },
            broadcastItem: () => {
                $rootScope.$broadcast('handleBroadcast');
            },


            getErrorMesageByStatusCode: (statusCode, data) => {
                switch (statusCode) {
                    case 401:
                        return "Unauthorized";
                        
                    case 500:
                        return data && data.code
                            ? getMessageByInternalCode(data.code)
                            : "An error has occurred. Please contact your administrator!";
                        
                    case 404:
                        return "Resource not found";
                        
                    case 400:
                        return "Bad request. Resource not found";
                        
                    case 2200:
                        return "File is not *.xls or *.xlsx";

                    // Filter errors
                    case 4001:
                        return "A filter by this name already exists, please enter a unique name and press save.";
                        
                    case 4002:
                        return "A filter by this name already exists, please enter a unique name and press save.";
                        
                    case 4003:
                        return "A filter name must be provided before pressing save.";
                        
                    case 4004:
                        return "A filter name cannot be the save as a Standard Filter.";
                        
                    // Portfolio errors
                    case 5001:
                        return "Portfolio is null";
                        
                    case 5002:
                        return "Portfolio id is null!";                  
                        
                    case 5003:
                        return "You are not authorised to change the status of the portfolio!";
                        
                    case 5004:
                        return "You are not authorised to delete the portfolio!";
                        
                    case 5005:
                        return "Portfolio is null!";
                        
                    case 5006:
                        return "Portfolio is not correct!";
                        
                    case 5007:
                        return "Portfolio is not correct!";
                        
                    case 5008:
                        return "You are not authorised to rename the portfolio!";
                        
                    case 5009:
                        return "This portfolio name already exists, please enter a unique name and try again!";
                        
                    case 5010:
                        return "Portfolio name is null!";
                        
                    case 5011:
                        return "Portfolio is no longer shared within the account!";
                        
                    case 5012:
                        return "UserId claim is null!";
                        
                    case 5013:
                        return "AccountId claim is null!";
                        
                    case 5014:
                        return "You are not authorised!";
                        
                    case 5015:
                        return "Portfolio is no longer available!";
                        
                    case 5103:
                        return "The company already exists in the selected portfolio!";
                        
                    case 5104:
                        return "You are not authorised to add company to portfolio!";
                                          
                    case 5105:
                        return "The item(s) could not be added to your portfolio.Please contact your client advisor for details.";

                    //Portfolio securities
                    case 5200:
                        return "The path is incorect!";
                        
                    case 5201:
                        return "There are securities that don't corespond with companies!";
                        
                    case 5202:
                        return "Selected file structure not valid. Please select a file with identical structure as the downloaded template format."
                        
                    case 5203:
                        return "Select a file for upload!";
                        
                    case 5210:
                        return "Please upload a valid file format (.xls or .xlsx)";
                        
                    // Company errors
                    case 6014:
                        return "You do not have the necessary rights to access this page. Please contact your client advisor for details.";
                        
                    // end Company errors
                    default:
                        return "Unknown error";
                }
            },
            errorCallback: (error, status, internalCode) => {
                if (error != "") {
                    notificationFactory.error(error.exceptionMessage, error.message);
                } else {
                    notificationFactory.error("", staticObjects.getErrorMesageByStatusCode(status, internalCode));
                }
            },
            initSignalR: () => {
                if ($rootScope.authData && $rootScope.authData.access_token) {
                    $.connection.hub.qs = { "access_token": $rootScope.authData.access_token };
                    $.connection.hub.start()
                        .done(() => {
                        })
                        .fail(error => {
                            //alert(error.message);
                            notificationFactory.error("SignalR failed to initialize!\n" + error.message, "SignalR error");
                        });
                }
            },
            reportStatus: {
                Requested: 'Requested',
                Running: 'Running',
                Finished: 'Finished',
                Failed: 'Failed',
            },
            clearUserInfo: () => {
                $rootScope.userInfo = null;
                $rootScope.authData = new Authentication.AuthData();
            },
            redirectToLogin: () => {
                if ($location.path() != '/login') {
                    $location.url('/login');
                }
            },
            redirectToDefault: (redirectTo?: string) => {
                if (redirectTo) {
                    $location.url(redirectTo);
                }
                else {
                    if ($location.path() != '/') {
                        $location.url('/');
                    }
                }
            },         
            redirectToLink: (link) => {
                if ($location.path() != link) {
                    $location.url(link);
                }
            },
            authDataIsExpired: (authData: Authentication.AuthData) => {
                if (!authData.loginTime) {
                    return true;
                }
                var day = authData.loginTime.getDay();
                var month = authData.loginTime.getMonth();
                var year = authData.loginTime.getFullYear();
                var hours = authData.loginTime.getHours();
                var minutes = authData.loginTime.getMinutes();
                var seconds = authData.loginTime.getSeconds();

                var endDate = new Date(year, month, day, hours, minutes, seconds + authData.expires_in);////
                var now = new Date();

                if (endDate > now) {
                    return true;
                } else {
                    return false;
                }
            },
            eventsServiceBaseUrl: "/eventsserv",
            screeningExportDetails: null
        };
        return staticObjects;
    }]);
}